<template>
  <div class="index">
    <div class="input">
      <div style="position: relative">
        <el-input
          v-model="input"
          @input="getSuggestion"
          @keyup.enter.native="searchHandler"
          @focus="focus"
          @blur="blur"
          type="text"
          id="place"
          placeholder="请输入地点"
        >
          <el-button slot="append" @click="ok">确定</el-button>
        </el-input>
        <el-card class="card" v-if="isSearch">
          <ul id="suggestionList">
            <li
              class="li"
              v-for="(item, index) in poiList"
              :key="index"
              style="list-style: none"
              @mousedown="chooseAdd(item)"
            >
              <span class="title">{{ item.title }}</span>
              <span class="add" style="color: #999999"
                >{{ item.city }}{{ item.district }}</span
              >
            </li>
          </ul>
        </el-card>
      </div>
    </div>

    <div id="container"></div>
  </div>
</template>
<script>
let map, marker, polygon, center, geocoder, ap, infoWindow, search;
export default {
  name: "mapc",
  props: {
    positionc: {
      type: [Object, String, Number],
      default: {
        longitude: 0, //经度
        latitude: 0, //纬度
        city: "",
      },
    },
  },
  data() {
    return {
      position: [
        {
          longitude: 0, //经度
          latitude: 0, //纬度
          city: "",
        },
      ],

      input: "",
      isSearch: false,
      jiaodian: false,
      poiList: [],
      chooseAddObj: {},
      btnFlag: false,
    };
  },
  methods: {
    searchHandler(e) {
      // console.log('searchHandler')
    },
    focus(e) {
      if (this.input.trim()) {
        this.isSearch = true;
      } else {
        this.isSearch = false;
      }
      this.jiaodian = true;
    },

    ok() {
      // console.log(this.chooseAddObj)
      if (!this.btnFlag) {
        // console.log(2)
        return;
      }

      if (this.chooseAddObj.title) {
        geocoder
          .getAddress({ location: this.chooseAddObj.location })
          .then((result) => {
            map.setCenter(
              new TMap.LatLng(
                result.result.location.lat,
                result.result.location.lng
              )
            );
            center = new TMap.LatLng(
              result.result.location.lat,
              result.result.location.lng
            );
            marker.setMap(null);
            marker = null;
            marker = new TMap.MultiMarker({
              map: map,
              styles: {
                // 点标记样式
                marker: new TMap.MarkerStyle({
                  width: 20, // 样式宽
                  height: 30, // 样式高
                  anchor: { x: 10, y: 30 }, // 描点位置
                }),
              },
              geometries: [
                // 点标记数据数组
                {
                  // 标记位置(纬度，经度，高度)
                  position: center,
                  id: "marker",
                },
              ],
            });
            // console.log(result)
            let xy =
              result.result.location.lng + "," + result.result.location.lat;
            let ds =
              result.result.formatted_addresses.standard_address +
              result.result.formatted_addresses.recommend;
            this.$emit("changeOrderDetails", ds, xy);
            this.$emit("innderClose");
            this.btnFlag = false;
          });
      } else {
      }
    },
    blur(e) {
      // console.log('blur')
      this.jiaodian = false;
      this.isSearch = false;
    },
    chooseAdd(item) {
      // console.log(item)
      this.chooseAddObj = item;
      this.input = item.title;
      // let location = new TMap.LatLng(item);
      geocoder.getAddress({ location: item.location }).then((result) => {
        if (result.status == 0) {
          map.setCenter(
            new TMap.LatLng(
              result.result.location.lat,
              result.result.location.lng
            )
          );
          center = new TMap.LatLng(
            result.result.location.lat,
            result.result.location.lng
          );
          marker.setMap(null);
          marker = null;
          marker = new TMap.MultiMarker({
            map: map,
            styles: {
              // 点标记样式
              marker: new TMap.MarkerStyle({
                width: 20, // 样式宽
                height: 30, // 样式高
                anchor: { x: 10, y: 30 }, // 描点位置
              }),
            },
            geometries: [
              // 点标记数据数组
              {
                // 标记位置(纬度，经度，高度)
                position: center,
                id: "marker",
              },
            ],
          });
        }
      });

      // this.getSuggestion()
    },

    getSuggestion(e) {
      var suggestionList = [];
      var search = new TMap.service.Search({ pageSize: 10 }); // 新建一个地点搜索类
      var suggest = new TMap.service.Suggestion({
        // 新建一个关键字输入提示类
        pageSize: 10, // 返回结果每页条目数
        region: "北京", // 限制城市范围
        regionFix: false, // 搜索无结果时是否固定在当前城市
      });
      var markers = new TMap.MultiMarker({
        map: map,
        geometries: [],
      });
      var infoWindowList = Array(10);
      var keyword = this.input;
      if (keyword) {
        suggest
          .getSuggestions({ keyword: keyword, location: map.getCenter() })
          .then((result) => {
            // 以当前所输入关键字获取输入提y示
            // console.log(result)
            this.poiList = result.data;
            this.btnFlag = true;
            this.chooseAddObj = this.poiList[0];
          })
          .catch((error) => {
            console.log(error);
          });
      }
    },
    initMap() {
      //定义地图中心点坐标
      center = new TMap.LatLng(this.position.latitude, this.position.longitude);
      //定义map变量，调用 TMap.Map() 构造函数创建地图
      map = new TMap.Map(document.getElementById("container"), {
        center: center, //设置地图中心点坐标
        zoom: 17.2, //设置地图缩放级别
      });
      geocoder = new TMap.service.Geocoder();
      marker = new TMap.MultiMarker({
        map: map,
        styles: {
          // 点标记样式
          marker: new TMap.MarkerStyle({
            width: 20, // 样式宽
            height: 30, // 样式高
            anchor: { x: 10, y: 30 }, // 描点位置
          }),
        },
        geometries: [
          // 点标记数据数组
          {
            // 标记位置(纬度，经度，高度)
            position: center,
            id: "marker",
          },
        ],
      });
      this.mapClick();
    },
    mapClick() {
      map.on("click", (evt) => {
        center = new TMap.LatLng(
          evt.latLng.lat.toFixed(6),
          evt.latLng.lng.toFixed(6)
        );
        if (evt.poi) {
          marker.setMap(null);
          marker = null;
          marker = new TMap.MultiMarker({
            map: map,
            styles: {
              // 点标记样式
              marker: new TMap.MarkerStyle({
                width: 20, // 样式宽
                height: 30, // 样式高
                anchor: { x: 10, y: 30 }, // 描点位置
              }),
            },
            geometries: [
              // 点标记数据数组
              {
                // 标记位置(纬度，经度，高度)
                position: center,
                id: "marker",
              },
            ],
          });
          this.input = evt.poi.name;
          this.getSuggestion();
          console.log(evt, this.poiList);
        }
      });
    },
  },
  mounted() {
    this.position = this.positionc;
    // this.getMyLocation()

    this.initMap();
  },
  watch: {
    positionc: {
      handler(val, oldVal) {
        this.position = val;
        // this.initMap()
        map.setCenter(
          new TMap.LatLng(this.position.latitude, this.position.longitude)
        );
        center = new TMap.LatLng(
          this.position.latitude,
          this.position.longitude
        );
        marker.setMap(null);
        marker = null;
        marker = new TMap.MultiMarker({
          map: map,
          styles: {
            // 点标记样式
            marker: new TMap.MarkerStyle({
              width: 20, // 样式宽
              height: 30, // 样式高
              anchor: { x: 10, y: 30 }, // 描点位置
            }),
          },
          geometries: [
            // 点标记数据数组
            {
              // 标记位置(纬度，经度，高度)
              position: center,
              id: "marker",
            },
          ],
        });
        console.log(val, "ccccccccccccccccccccccccccccccc");
        this.input = "";
        // this.getMyLocation()
      },
      deep: true,
    },
    input() {
      if (this.jiaodian) {
        if (this.input.trim()) {
          this.isSearch = true;
        } else {
          this.isSearch = false;
        }
      }
    },
  },
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 94.7%;
  position: absolute;
  left: 0;
  top: 50px;
  z-index: 98;
}
.input {
  position: absolute;
  z-index: 99;
  width: 20%;
  transform: translate(-50%, -50%);
  left: 15%;
  top: 7.5%;
}
.card {
  position: absolute;
  z-index: 99;
  width: 100%;
  top: 100%;
}
#suggestionList .li {
  padding: 10px;
  cursor: pointer;
}
#suggestionList .li:hover {
  background: #ebebeb;
}
/deep/.card .el-card__body {
  padding: 0;
}
#suggestionList .li .title,
#suggestionList .li .add {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
